import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/stock_move_line_odoo_api.dart';
import 'package:flutter_admin/models/odoo/stock_move_line.dart';
import 'package:flutter_admin/models/user_info.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/finished_in_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/finish_in.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';

import 'location_in_search_dialog.dart';

class LocationInSearchList extends StatefulWidget {
  LocationInSearchList({Key? key}) : super(key: key);

  @override
  _LocationInSearchListState createState() => _LocationInSearchListState();
}

class _LocationInSearchListState extends State<LocationInSearchList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  StockMoveLine stockMoveLine = StockMoveLine();
  List<StockMoveLine> selectedList = [];
  //车间
  List<SelectOptionVO> workshopList = [];
  //源库房
  List<SelectOptionVO> locationList = [];

  UserInfo userInfo = StoreUtil.getCurrentUserInfo();

  DateFormat format= DateFormat('yyyy-MM-dd');
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    ResponseBodyApi res = await StockMoveLineOdooApi.getLocation(userInfo.userId);
    if (res.success!){
      for(var i = 0; i < res.data.length; i++){
        locationList.add(SelectOptionVO(value: res.data[i]["locaiton_id"].toString(),label: res.data[i]["locaiton_name"]));
      }
      if(res.data.length == 1){
        stockMoveLine.locationDestId = res.data[0]["location_id"].toString();
        setState(() {});
        _query();
      }
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    UserInfo userInfo = StoreUtil.getCurrentUserInfo();
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CrySelect(
            width: 380,
            label: '库房',
            dataList: locationList,
            value: stockMoveLine.locationId,
            onSaved: (v) {
              stockMoveLine.locationId = v;
            },
          ),
          CrySelectDate(
            context,
            width: 180,
            label: '操作开始时间',
            value: stockMoveLine.createDateStart,
            lastDate: isNotBlank(stockMoveLine.createDateEnd)
                ? format.parse(stockMoveLine.createDateEnd!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              stockMoveLine.createDateStart = v;
              setState(() {});
            },
            onSaved: (v) {
              stockMoveLine.createDateStart = v;
            },
          ),
          CrySelectDate(
            context,
            width: 180,
            label: '操作结束时间',
            value: stockMoveLine.createDateEnd,
            firstDate: isNotBlank(stockMoveLine.createDateStart)
                ? format.parse(stockMoveLine.createDateStart!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              stockMoveLine.createDateEnd = v;
              setState(() {});
            },
            onSaved: (v) {
              stockMoveLine.createDateEnd = v;
            },
          ),
          CryInput(
            width: 160,
            label: '物料编码',
            value: stockMoveLine.productCode,
            onSaved: (v) {
              stockMoveLine.productCode = v;
            },
          ),
          CryInput(
            width: 160,
            label: '物料名称',
            value: stockMoveLine.productName,
            onSaved: (v) {
              stockMoveLine.productName = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('入库单号')),
        DataColumn(label: Text('生产订单号')),
        DataColumn(label: Text('批次号')),
        DataColumn(label: Text('物料编码')),
        DataColumn(label: Text('物料名称')),
        DataColumn(label: Text('规格型号')),
        DataColumn(label: Text('计划数量')),
        DataColumn(label: Text('实际数量')),
        DataColumn(label: Text('计量单位')),
        DataColumn(label: Text('入库类型')),
        // DataColumn(label: Text('发方')),
        DataColumn(label: Text('发方位置')),
        // DataColumn(label: Text('收方')),
        DataColumn(label: Text('收方位置')),
        DataColumn(label: Text('操作人')),
        DataColumn(label: Text('操作时间')),
        DataColumn(label: Text('备注')),
      ],
      getCells: (m) {
        StockMoveLine stockMoveLine = StockMoveLine.fromMap(m);
        return [
          DataCell(Text(stockMoveLine.serialNumber ?? '--')),
          DataCell(Text(stockMoveLine.productionNo ?? '--')),
          DataCell(Text(stockMoveLine.lotName ?? '--')),
          DataCell(Text(stockMoveLine.productCode ?? '--')),
          DataCell(Text(stockMoveLine.productName ?? '--')),
          DataCell(Text(stockMoveLine.productDesc ?? '--')),
          DataCell(Text(stockMoveLine.planQty.toString())),
          DataCell(Text(stockMoveLine.qtyDone.toString())),
          DataCell(Text(stockMoveLine.productUomName ?? '--')),
          DataCell(Text(stockMoveLine.jobTypeName ?? '--')),
          DataCell(Text(stockMoveLine.jobJson ?? '--')),
          DataCell(Text(stockMoveLine.locationName ?? '--')),
          DataCell(Text(stockMoveLine.createName ?? '--')),
          DataCell(Text(Utils.timeUTC(stockMoveLine.writeDate))),
          DataCell(Text(stockMoveLine.remark ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Wrap(
            children: [
              isDisplayDesktop(context) ? form : Container(),
              Padding(
                padding: EdgeInsets.only(top: 24),
                child: isDisplayDesktop(context) ? buttonBar : Container(),
              )
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _reset() {
    stockMoveLine = StockMoveLine();
    formKey.currentState!.reset();
    tableKey.currentState?.pageTo(0);
    tableKey.currentState?.loadData(PageModel());
    if(locationList.length == 1){
      stockMoveLine.locationDestId = locationList[0].value.toString();
      setState(() {});
      _query();
    }
    setState(() {});
    // _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    if (isBlank(stockMoveLine.locationId)) {
      tableKey.currentState?.pageTo(0);
      tableKey.currentState?.loadData(PageModel());
      CryUtils.message("请选择库房位置");
      return;
    }
    ResponseBodyApi responseBodyApi = await StockMoveLineOdooApi.page(
        data: {"page": page, "domainList": stockMoveLine.toInSearchDomainList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: LocationInSearchDialog(),
      ),
    ).then((v) {
      if (v != null) {
        stockMoveLine = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<StockMoveLine>((e) => StockMoveLine.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.dmsFile) {
          // _scan();
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
      ],
    );
  }
}
